package com.wsgxj.controller.sys;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.wsgxj.util.PasswordUtil;
import com.wsgxj.vo.R;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;


@Controller
public class SysLoginController {
	
	@Autowired
	private Producer producer;

	@RequestMapping("/sys/login")
	@ResponseBody
	public R login(@RequestBody Map<String, String> userinfo) {
		
		String username = userinfo.get("username");
		String password = userinfo.get("password");
		String kaptcha = userinfo.get("kaptcha");
		String rememberMeStr = userinfo.get("rememberMe");
		
		Subject subject = SecurityUtils.getSubject();
		Object kaptchao = subject.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if(kaptchao == null) {
			//throw new RRException("验证码失效");
			return R.error("验证码失效");
		}
		//清空session中的验证码
		subject.getSession().removeAttribute(Constants.KAPTCHA_SESSION_KEY);
		if(!kaptcha.equalsIgnoreCase(kaptchao.toString())) {
			return R.error("验证码不正确");
		}
		
		Boolean rememberMe = false;
		if(rememberMeStr != null) {
			rememberMe = true;
		}
		
		//密码加密
		password = PasswordUtil.md5(password, username);
		UsernamePasswordToken token = new UsernamePasswordToken(username,password);
		token.setRememberMe(rememberMe);
		try {
			subject.login(token);
		} catch (UnknownAccountException e) {
			return R.error(e.getMessage());
		} catch (IncorrectCredentialsException e) {
			return R.error(e.getMessage());
		} catch (LockedAccountException e) {
			return R.error(e.getMessage());
		} catch (AuthenticationException e) {
			return R.error(e.getMessage());
		}
		
		return R.ok();
	}
	
	@RequestMapping("/logout")
	public String logout() {
		SecurityUtils.getSubject().logout();
		return "redirect:/index";
	}
	
	@RequestMapping("/kaptcha.jpg")
	public void kaptcha(HttpServletResponse response) throws IOException {
		response.setHeader("Cache-Control", "no-store,no-cache");
		response.setContentType("image/jpeg");
		
		//生成文字
		String text = producer.createText();
		//生成图片
		BufferedImage image = producer.createImage(text);
		
		//保存到shiro session中
		SecurityUtils.getSubject().getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
		
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		out.flush();
	}
}
